import type { FormInstance } from 'element-plus'
import type { RuleItem } from 'async-validator'
import type {
  SystemUserStateType,
  SystemRoleStateType,
  SystemPostStateType
} from '~/store/system/typings'
import type { SystemUserOptionsPropsType, SystemUserDataItemType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElTreeSelect,
  ElDatePicker,
  ElRow,
  ElCol,
  ElButton,
  ElIcon,
  ElMessage
} from 'element-plus'
import { EditPen } from '@element-plus/icons-vue'
import useVuexGetters from '~/hooks/useVuexGetters'
import { GUTTER, SPAN_STYLE_DOUBLE } from '~/utils/const'
import { handleTrim, handleEnumValue } from '~/utils/util'
import { emailValidate } from '~/utils/validate'

export default defineComponent({
  name: 'SystemUserOptions',
  props: ['visible', 'type', 'record'],
  emits: ['cancel'],
  setup(props: SystemUserOptionsPropsType, { emit }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const formValues = reactive<SystemUserDataItemType>({
      roleId: [],
      postId: []
    })
    const title = { add: '新增', update: '编辑', read: '查看' }
    const systemUserState = useVuexGetters('systemUser', [
      // 'belongTenantSelectList',
      'belongTenantEnum',
      'userSexSelectList',
      'userSexEnum'
    ])
    const systemRoleState = useVuexGetters('systemRole', ['userRoleSelectList', 'userRoleEnum'])
    const systemDeptState = useVuexGetters('systemDept', ['parentDeptSelectList'])
    const systemPostState = useVuexGetters('systemPost', ['postSelectList', 'postEnum'])

    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    // 提交表单
    const handleSubmitForm = () => {
      const { type } = props
      if (!ruleFormRef.value) return
      ruleFormRef.value.validate(async (valid) => {
        if (!valid) return
        const params = { ...formValues }
        params.account = params.account && handleTrim(params.account)
        if (!params.id) {
          params.password = params.password && handleTrim(params.password)
          params.password2 = params.password2 && handleTrim(params.password2)
        }
        // params.name = params.name && handleTrim(params.name)
        params.code = params.code && handleTrim(params.code)
        params.realName = params.realName && handleTrim(params.realName)
        params.phone = params.phone && handleTrim(params.phone)
        params.roleId = (params.roleId as string[])?.join?.(',')
        params.postId = (params.postId as string[])?.join?.(',')
        const res = await store.dispatch(
          type === 'add' ? 'systemUser/AddSystemUserInfo' : 'systemUser/UpdateSystemUserInfo',
          params
        )
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          handleCloseModal()
        }
      })
    }

    // 切换所属租户的回调
    const handleChangeTenantId = (value: string) => {
      // const { type } = props
      // if (type !== 'read') {
      //   formValues.roleId = ''
      //   formValues.deptId = ''
      //   formValues.postId = ''
      // }
      if (value) {
        // 获取所属角色下拉列表
        store.dispatch('systemRole/GetUserRoleSelectList', { tenantId: value })
        // 获取部门树形下拉列表
        store.dispatch('systemDept/GetSystemDeptTree', { tenantId: value })
      }
    }

    // 切换所属部门的回调
    const handleChangeDeptId = (value: string) => {
      const { type } = props
      if (type !== 'read') {
        formValues.postId = undefined
      }
      if (value) {
        store.dispatch('systemPost/GetPostSelectListByDeptId', { deptId: value })
      }
    }

    // 密码校验
    const handleValidatePass: RuleItem['asyncValidator'] = (rule, value, callback) => {
      if (!value) callback(new Error('请输入确认密码'))
      if (formValues.password !== value) callback(new Error('两次输入密码不一致!'))
      callback()
    }

    onMounted(() => {
      const { type } = props
      if (props.record?.id) {
        handleChangeTenantId(props.record?.tenantId!)
        handleChangeDeptId(props.record?.deptId!)
        Object.assign(
          formValues,
          type === 'update'
            ? {
                id: props.record?.id,
                account: props.record?.account,
                // tenantId: props.record?.tenantId,
                // name: props.record?.name,
                code: props.record?.code,
                realName: props.record?.realName,
                roleId: (props.record?.roleId as string)?.split(',') || [],
                deptId: props.record?.deptId,
                postId: (props.record?.postId as string)?.split(',') || [],
                phone: props.record?.phone,
                email: props.record?.email,
                sex: props.record?.sex,
                birthday: props.record?.birthday
              }
            : props.record
        )
      } else {
        const sabeUserInfo: any = localStorage.getItem('saber-userInfo') || null
        const userinfo = JSON.parse(sabeUserInfo)
        const { tenantId } = userinfo.content
        handleChangeTenantId(tenantId)
      }
    })

    return () => {
      const { type, visible } = props
      return (
        <ElDialog
          title={(title[type] as string) || '查看'}
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
          v-slots={
            type !== 'read' && {
              footer: () => (
                <>
                  <ElButton type="primary" onClick={handleSubmitForm}>
                    <ElIcon>
                      <EditPen />
                    </ElIcon>
                    &nbsp; {type === 'add' ? '保存' : '修改'}
                  </ElButton>
                  <ElButton onClick={handleCloseModal}>取消</ElButton>
                </>
              )
            }
          }
        >
          <ElForm label-width="100px" ref={ruleFormRef} model={formValues}>
            <ElRow gutter={GUTTER}>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="account"
                  label="登录账号"
                  rules={[{ required: true, message: '请输入登录账号' }]}
                >
                  {type === 'read' ? (
                    formValues.account
                  ) : (
                    <ElInput
                      v-model={formValues.account}
                      placeholder="请输入登录账号"
                      disabled={type === 'update'}
                    />
                  )}
                </ElFormItem>
              </ElCol>
              {/* <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="tenantId"
                  label="所属租户"
                  rules={[{ required: true, message: '请输入所属租户' }]}
                >
                  {type === 'read' ? (
                    systemUserState?.belongTenantEnum.value?.[formValues.tenantId!] ||
                    formValues.tenantId
                  ) : (
                    <ElSelect
                      v-model={formValues.tenantId}
                      placeholder="请输入所属租户"
                      onChange={handleChangeTenantId}
                    >
                      {systemUserState.belongTenantSelectList.value?.map(
                        (item: SystemUserStateType['belongTenantEnum']) => (
                          <ElOption
                            key={item?.tenantId}
                            value={item?.tenantId!}
                            label={item?.tenantName}
                          />
                        )
                      )}
                    </ElSelect>
                  )}
                </ElFormItem>
              </ElCol> */}
              {type === 'add' && (
                <>
                  <ElCol {...SPAN_STYLE_DOUBLE}>
                    <ElFormItem
                      prop="password"
                      label="密码"
                      rules={[{ required: true, message: '请输入密码' }]}
                    >
                      <ElInput
                        v-model={formValues.password}
                        placeholder="请输入密码"
                        onInput={() => ruleFormRef.value?.validateField('password2')}
                      />
                    </ElFormItem>
                  </ElCol>
                  <ElCol {...SPAN_STYLE_DOUBLE}>
                    <ElFormItem
                      prop="password2"
                      label="确认密码"
                      rules={[{ required: true, asyncValidator: handleValidatePass }]}
                    >
                      <ElInput v-model={formValues.password2} placeholder="请输入确认密码" />
                    </ElFormItem>
                  </ElCol>
                </>
              )}
              {/* <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="name"
                  label="用户昵称"
                  rules={[{ required: true, message: '请输入用户昵称' }]}
                >
                  {type === 'read' ? (
                    formValues.name
                  ) : (
                    <ElInput v-model={formValues.name} placeholder="请输入用户昵称" />
                  )}
                </ElFormItem>
              </ElCol> */}
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="realName"
                  label="用户姓名"
                  rules={[{ required: true, message: '请输入用户姓名' }]}
                >
                  {type === 'read' ? (
                    formValues.realName
                  ) : (
                    <ElInput v-model={formValues.realName} placeholder="请输入用户姓名" />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="roleId"
                  label="所属角色"
                  rules={[{ required: true, message: '请输入所属角色' }]}
                >
                  {type === 'read' ? (
                    formValues.roleName
                  ) : (
                    <ElSelect v-model={formValues.roleId} multiple placeholder="请输入所属角色">
                      {systemRoleState.userRoleSelectList.value?.map(
                        (item: SystemRoleStateType['userRoleEnum']) => (
                          <ElOption key={item?.id} value={item?.id!} label={item?.title} />
                        )
                      )}
                    </ElSelect>
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="deptId"
                  label="所属部门"
                  rules={[{ required: true, message: '请输入所属部门' }]}
                >
                  {type === 'read' ? (
                    formValues.deptName
                  ) : (
                    <ElTreeSelect
                      v-model={formValues.deptId}
                      placeholder="请输入所属部门"
                      data={systemDeptState.parentDeptSelectList.value}
                      checkStrictly
                      renderAfterExpand={false}
                      props={{
                        label: 'title',
                        value: 'id'
                      }}
                      onChange={handleChangeDeptId}
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="code"
                  label="用户编号"
                  rules={[{ required: false, message: '请输入用户编号' }]}
                >
                  {type === 'read' ? (
                    formValues.code
                  ) : (
                    <ElInput v-model={formValues.code} placeholder="请输入用户编号" />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="postId"
                  label="所属岗位"
                  rules={[{ required: true, message: '请输入所属岗位' }]}
                >
                  {type === 'read' ? (
                    (formValues?.postId as string)
                      ?.split(',')
                      ?.map((item) => handleEnumValue(systemPostState?.postEnum.value, item))
                  ) : (
                    <ElSelect v-model={formValues.postId} multiple placeholder="请输入所属岗位">
                      {systemPostState.postSelectList.value?.map(
                        (item: SystemPostStateType['postEnum']) => (
                          <ElOption key={item?.id} value={item?.id!} label={item?.postName} />
                        )
                      )}
                    </ElSelect>
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="phone"
                  label="手机号码"
                  rules={[
                    { required: true, message: '请输入手机号码' },
                    {
                      min: 11,
                      max: 11,
                      message: '不合法的手机号码格式!'
                    }
                  ]}
                >
                  {type === 'read' ? (
                    formValues.phone
                  ) : (
                    <ElInput
                      v-model={formValues.phone}
                      disabled={type === 'update'}
                      placeholder="请输入手机号码"
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="email"
                  label="电子邮箱"
                  rules={[
                    { required: false, message: '请输入电子邮箱' },
                    {
                      pattern: emailValidate,
                      message: '不合法的电子邮箱格式!'
                    }
                  ]}
                >
                  {type === 'read' ? (
                    formValues.email
                  ) : (
                    <ElInput v-model={formValues.email} placeholder="请输入电子邮箱" />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="sex"
                  label="用户性别"
                  rules={[{ required: false, message: '请选择用户性别' }]}
                >
                  {type === 'read' ? (
                    systemUserState?.userSexEnum.value?.[formValues.sex!] || formValues.sex
                  ) : (
                    <ElSelect v-model={formValues.sex} placeholder="请选择用户性别">
                      {systemUserState.userSexSelectList.value?.map(
                        (item: SystemUserStateType['userSexEnum']) => (
                          <ElOption key={item?.key} value={item?.key!} label={item?.value} />
                        )
                      )}
                    </ElSelect>
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="birthday"
                  label="用户生日"
                  rules={[{ required: false, message: '请选择用户生日' }]}
                >
                  {type === 'read' ? (
                    formValues.birthday
                  ) : (
                    <ElDatePicker
                      v-model={formValues.birthday}
                      placeholder="请选择用户生日"
                      valueFormat="YYYY-MM-DD hh:mm:ss"
                    />
                  )}
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElForm>
        </ElDialog>
      )
    }
  }
})
